﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Validation.sp2010.Classes;
using System.Collections.Generic;
using Validation.sp2010.Helper;
using Microsoft.SharePoint;
using System.Linq;
using Validation.sp2010.WorkFlow.ValidationWorkflow;
namespace Validation.sp2010.CONTROLTEMPLATES.Validation.sp2010
{
    public partial class GridSteps : UserControl
    {
        #region Properties
        
        public string MsgModification
        {
            get
            {
                return HelperUtilities.GetResources("label_modification", SPContext.Current.Web.Language);
            }
        }

        #endregion
        #region Const label
        public static readonly string label_step_task = HelperUtilities.GetResources("label_step_task", SPContext.Current.Web.Language);
        public static readonly string label_step_mail = HelperUtilities.GetResources("label_step_mail", SPContext.Current.Web.Language);
        public static readonly string label_from = HelperUtilities.GetResources("label_from", SPContext.Current.Web.Language);

        public static readonly string label_detail_task = HelperUtilities.GetResources("label_detail_task", SPContext.Current.Web.Language);
        public static readonly string label_detail_mail = HelperUtilities.GetResources("label_detail_mail", SPContext.Current.Web.Language);
        public static readonly string label_secondary = HelperUtilities.GetResources("label_secondary", SPContext.Current.Web.Language);

        #endregion

        #region const state

        private const string stateListSteps = "AllStep"; 

        #endregion

     #region Event
		   protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void RepeaterSteps_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
        {
            //delete item
            if (e.CommandName == "Delete")
            {
                List<StepWF> steps = ViewState[stateListSteps] as List<StepWF>;
                steps.RemoveAt(e.Item.ItemIndex);

                List<StepModel> modelSteps = new List<StepModel>();
                steps.ForEach(s => modelSteps.Add(new StepModel(s)));

                RepeaterSteps.DataSource = modelSteps;
                RepeaterSteps.DataBind();
            }
            //code Edit
            else if (e.CommandName == "Edit")
            {
                List<StepWF> steps = ViewState[stateListSteps] as List<StepWF>;
                StepWF step = steps[e.Item.ItemIndex];

                DropDownList list = e.Item.FindControl("IfValidOption") as DropDownList;
                if (list != null)
                    step.NextStepValidation = int.Parse(list.SelectedValue);

                list = e.Item.FindControl("IfRefuseOption") as DropDownList;
                if (list != null)
                    step.NextStepRefuse = int.Parse(list.SelectedValue);

                list = e.Item.FindControl("DropDownFinal") as DropDownList;
                if (list != null)
                    step.IsFinal = list.SelectedValue == "1";

                list = e.Item.FindControl("DropDownStart") as DropDownList;
                if (list != null)
                    step.IsInitial = list.SelectedValue == "1";


            }
            else
            {
                  List<StepWF> steps = ViewState[stateListSteps] as List<StepWF>;
                StepWF step = steps[e.Item.ItemIndex];

                Parent.EditStep(step);
            }
        }

        protected void RepeaterSteps_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DropDownList list = e.Item.FindControl("IfValidOption") as DropDownList;
            if (list != null)
                list.SelectedValue = (e.Item.FindControl("NextValidate") as HiddenField).Value;


            list = e.Item.FindControl("IfRefuseOption") as DropDownList;
            if (list != null)
                list.SelectedValue = (e.Item.FindControl("Nextrefuse") as HiddenField).Value;


            list = e.Item.FindControl("DropDownFinal") as DropDownList;
            if (list != null)
                list.SelectedValue = (e.Item.FindControl("IsFinal") as HiddenField).Value;


            list = e.Item.FindControl("DropDownStart") as DropDownList;
            if (list != null)
                list.SelectedValue = (e.Item.FindControl("IsStart") as HiddenField).Value;




        }

        protected void RepeaterSteps_DataBinding(object sender, EventArgs e)
        {
            List<StepModel> modelSteps = (sender as Repeater).DataSource as List<StepModel>;

            modelSteps.ForEach(s =>
            {
                List<ValidOption> options = new List<ValidOption>() { new ValidOption() { Option = 0, Display = "Terminer" } };
                modelSteps.ForEach(s1 =>
                {
                    if (s.Sequence != s1.Sequence)
                        options.Add(new ValidOption() { Option = s1.Sequence, Display = "Etape " + s1.Sequence });
                });

                s.OptionsValid = options;
                s.OptionsRefuse = options;
            });

        }
   
	#endregion 
        #region public method

        public Rules Parent { get; set; }

        
        /// <summary>
        /// load all data from association pages
        /// </summary>
        /// <param name="steps"></param>
        public void LoadData(List<StepWF> steps)
        {

            ViewState[stateListSteps] = steps;

            List<StepModel> modelSteps = new List<StepModel>();
            steps.ForEach(s => modelSteps.Add(new StepModel(s)));
            
            RepeaterSteps.DataSource = modelSteps;
            RepeaterSteps.DataBind();
        }



        /// <summary>
        /// Add new step
        /// </summary>
        /// <param name="step"></param>
        public void AddStep(StepWF step)
        {
            //Read steps from repeater
            //load steps
            //write repeter

            List<StepWF> steps = (ViewState[stateListSteps] as List<StepWF>);
            int sequence = steps.Count == 0 ? 1 : steps.Max(s => s.Sequence) + 1;
            step.Sequence = sequence;
            steps.Add(step);

            List<StepModel> modelSteps = new List<StepModel>();
            steps.ForEach(s => modelSteps.Add(new StepModel(s)));

            RepeaterSteps.DataSource = modelSteps;
            RepeaterSteps.DataBind();

        }

        /// <summary>
        /// Edit step
        /// </summary>
        /// <param name="step"></param>
        public void EditStep(StepWF step)
        {
            List<StepWF> steps = (ViewState[stateListSteps] as List<StepWF>);

            int index= steps.FindIndex(s => s.Sequence == step.Sequence);

            step.NextStepRefuse = steps[index].NextStepRefuse;
            step.NextStepValidation = steps[index].NextStepValidation;

            steps[index] = step;

            List<StepModel> modelSteps = new List<StepModel>();
            steps.ForEach(s => modelSteps.Add(new StepModel(s)));

            RepeaterSteps.DataSource = modelSteps;
            RepeaterSteps.DataBind();
        }
        /// <summary>
        /// Return all steps with the new properties (ifValide, ifRefuse, nextValidation, nextRefuse)
        /// </summary>
        /// <returns></returns>
        public List<StepWF> GetAllSteps()
        {
            List<StepWF> steps = (ViewState[stateListSteps] as List<StepWF>);

            int initialStepCount = steps.Where(s => s.IsInitial).ToList().Count;
            if (initialStepCount != 1)
            {
                Error.Text = HelperUtilities.GetResources("error_steps_initial", SPContext.Current.Web.Language);
                return null;
            }

            int finalStepCount = steps.Where(s => s.IsFinal).ToList().Count;
            if (finalStepCount == 0)
            {
                Error.Text = HelperUtilities.GetResources("error_steps_final", SPContext.Current.Web.Language);
                return null;
            }

            return steps;
        } 
        #endregion

        #region private method
        
        #endregion
    }

    [Serializable]
    public class StepModel
    {

        public string Title { get; set; }
        public string Type { get; set; }
        public string Actor { get; set; }
        public string Details { get; set; }
        public int Sequence { get; set; }

        public string IsFinal { get; set; }
        public string IsStart { get; set; }

        public int NextValidation { get; set; }
        public int Nextrefuse { get; set; }

        public bool IsTask { get; set; }
        public bool IsMail { get; set; }
        
        public List<ValidOption> OptionsRefuse { get; set; }
        public List<ValidOption> OptionsValid { get; set; }
        public StepModel(StepWF step)
        {


            this.Title = step.Title;
            this.Actor = step.Actor.GetUserString(GridSteps.label_from, GridSteps.label_secondary);
            this.Sequence = step.Sequence;
            IsFinal = step.IsFinal ? "1" : "2";
            IsStart = step.IsInitial ? "1" : "2";
            NextValidation = step.NextStepValidation;
            Nextrefuse = step.NextStepRefuse;
            IsTask = step.TypeStep == TypeStep.Task;
            IsMail = step.TypeStep == TypeStep.Notfication;


            if (step.TypeStep == TypeStep.Task)
            {
                this.Details = string.Format(GridSteps.label_detail_task, step.ObjectDisplay,
                    step.BodyDisplay,
                    step.WithExtension.ToString(),
                    step.ForceValidation.ToString(),
                    step.NotifyUserByMail.ToString(),
                    step.ProlongedExtension.ToString());
                this.Type = GridSteps.label_step_task;
            }
            else
            {
                this.Details = string.Format(GridSteps.label_detail_mail, step.ObjectDisplay, step.BodyDisplay, step.CC_Mail != null ? step.CC_Mail.GetUserString(GridSteps.label_from, GridSteps.label_secondary) : "-");
                this.Type = GridSteps.label_step_mail;

            }

         

        }
    }

    [Serializable]
    //Drop Donw List
    public class ValidOption
    {
        public int Option { get; set; }
        public string Display { get; set; }
    }
}
